<template>
  <div class="bonusManage">
    <div>
      <label>日期</label>
      <el-date-picker
        v-model="value1"
        type="week"
        id="getWeek"
        @change="changePicker"
        format="yyyy 第 W 周"
        :picker-options="{firstDayOfWeek:1}"
        placeholder="选择周">
      </el-date-picker>

    </div>

    <div class='money'>
      <p>分红金额：
        <span>{{money}}元</span>
        <span v-if='data.executed'>已发放</span>
        <el-button v-loading="loading" type="danger"  style="margin-left: 20px" :disabled="disabled"  @click="apportionuUnissued"
                   v-if="hasPerm('orders:bonus:sharing')&&!data.executed" size="mini">
          发放加权奖励
        </el-button>
      </p>

    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
      <el-table-column label="ID" prop="id" align="center">
        <template slot-scope="scope">
          <span @click='goDetails(scope.row.id)' class="link-type">{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="avatar" label="头像" align="center">
        <template slot-scope="scope">
          <el-avatar :size="'large'" v-if="scope.row.avatar" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="用户名" width="150" align="center"></el-table-column>
      <!--<el-table-column prop="inviteUserId" label="邀请人ID" width="150" align="center"></el-table-column>-->

      <el-table-column label="分红金额" align="center">
        <template slot-scope="scope">
          <span>{{ preBonus }}</span>
        </template>
      </el-table-column>

    </el-table>
    <div class="pagination">
      <el-pagination
        v-if="showPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="nowPage"
        :page-size="limit"
        layout="total, prev, pager, next"
        :total="totalElement"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {ajax} from "@/api";
import {getYesterday} from "@/utils";
import {getToken} from "@/utils/auth";
import {parseTime} from '../../utils/index'
import {mapGetters} from "vuex";
import {userData, userEnable, userDel} from '@/api/user'
import {bonusSharing, bonusStatistics,} from '@/api/order'

export default {
  name: "bonusManage",
  data() {
    return {
      showPage: false,
      disabled: false,
      startTimeStamp:"",
      endTimeStamp:"",
      value1: "",
      money: 0.0,
      total: 0,
      month: 0,
      preBonus: 0,
      counted: 0,
      params: {
        startTime: 0,
        endTime: 0,
        week: 0,
        year: 0,
      },
      data: {},
      moneyParams: {
        startOfDay: '',
        token: getToken()
      },
      loading: false,
      tableData: [],
      limit: 10,
      nowPage: 1,
      totalElement: 0,
    };
  },
  watch: {
    nowPage(val) {
      this.getList();
    },
    limit(val) {
      this.getList();
    },
  },
  methods: {
    goDetails(id) {
      this.$router.push({
        path: `/userManage/modify/UserModify/${id}`,
      })
    },
    changePicker(val) {
      console.log(this.value1, "value1-changePicker");
      let preDate = new Date(this.value1.getTime() - 24 * 60 * 60 * 1000); //前一天
      let firstDay = parseTime(preDate, '{y}-{m}-{d} {h}:{i}:{s}');
      let firstDayTimestamp = new Date(firstDay).getTime();
      let firstDayFormat = parseTime(firstDay, '{y}-{m}-{d} {h}:{i}:{s}');
      let year = parseTime(firstDayFormat, '{y}');
      let month = parseTime(firstDayFormat, '{m}');
      let day = parseTime(firstDayFormat, '{d}');

      this.params.startTime = firstDayTimestamp;
      this.params.endTime = firstDayTimestamp + 7 * 24 * 60 * 60 * 1000 - 1;
      this.params.week = this.getYearWeek(year,month,day) - 1;
      this.params.year = parseTime(firstDay, '{y}');
      this.month = parseTime(firstDay, '{m}');
      console.log(this.params,"params-changePicker");
      this.getTodayMoney();
    },

    // 获取年的第几周的方法：
    getYearWeek(a, b, c){
      /*
      date1是当前日期
      date2是当年第一天
      d是当前日期是今年第多少天
      用d + 当前年的第一天的周差距的和在除以7就是本年第几周
      */
      var date1 = new Date(a, parseInt(b) - 1, c),
        date2 = new Date(a, 0, 1),
        d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
      return Math.ceil((d + ((date2.getDay() + 1) - 1)) / 7);
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.limit = val;
    },
    handleCurrentChange(val) {
      this.nowPage = val;
    },
    //点击未分成得到已分成
    apportionuUnissued() {
      this.loading = true
      this.disabled = true
      bonusSharing({
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        week: this.params.week,
        year: this.params.year,
      })
        .then((res) => {
          this.loading = false
          setTimeout(()=>{
            this.disabled = false
          },500)
          if (res.code === 200) {
            console.log(res,"res");
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.data.executed = true;
          } else {
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        });
    },
    //获得前一天的日期
    getYesterDay() {
      this.value1 = getYesterday(-1, "-");
    },

    //得到当前选择周的订单金额
    getTodayMoney() {
      bonusStatistics({
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        week: this.params.week,
        year: this.params.year,
      })
        .then((res) => {
          if (res.code === 200) {
            this.data = res.data;
            console.log(this.data, "this.data")
            this.money = parseFloat(Number(res.data.bonus * 0.01).toFixed(2));
            let totalPeople = res.data.totalPeople
            this.preBonus = parseFloat(Number(res.data.bonus / totalPeople * 0.01).toFixed(2));
          }
        });
    },

    //获得数据
    getList() {
      userData({
        inviter: 1,
        enable: 1,
        limit: this.limit,
        page: this.nowPage - 1,
      })
        .then((res) => {
          if (res.code === 200) {
            this.tableData = res.data;
            console.log(this.tableData,"分红列表");
            this.totalElement = res.total;
            this.showPage = true;
          }
        });
    },
    // 默认展示本周
    showWeekFirstDay() {
      var nowTemp = new Date();//当前时间
      var oneDayLong = 246060 * 1000;//一天的毫秒数
      var c_time = nowTemp.getTime();//当前时间的毫秒时间
      var c_day = nowTemp.getDay() || 7;//当前时间的星期几
      console.log(c_day,"当前时间的星期几");
      var m_time = c_time - (c_day - 1) * oneDayLong + 5 * 3600 * 24 * 1000;//当前周一的毫秒时间
      var monday = new Date(m_time);//设置周一时间对象
      console.log(monday,"设置周一时间对象");
      var mondayFormat = new Date(m_time).setHours(0, 0, 0, 0);//设置周一时间戳
      // var mondayFormat = new Date(m_time).setHours(23, 59, 59, 59);//设置周一时间戳

      let year = parseTime(monday, '{y}')
      let month = parseTime(monday, '{m}')
      let day = parseTime(monday, '{d}')

      console.log(year, month, day,"year, month, day,mounted");
      this.value1 = mondayFormat

      console.log(this.value1,"this.value1 mounted");
      this.params.startTime = mondayFormat
      this.params.endTime = mondayFormat + (7 * 24 * 60 * 60 * 1000 - 1000)

      this.params.week = this.getYearWeek(year, month, day) -1;
      this.params.year = parseTime(monday, '{y}')

      console.log(this.params,"this.params mounted");
      this.getTodayMoney();   //得到当前选择周的订单金额
    },
  },
  mounted() {
    this.showWeekFirstDay();
    this.getList();

  }
};
</script>

<style scoped>
  .bonusManage {
    margin: 20px;
  }

  .bonusManage div label {
    font-weight: 400;
    font-size: 14px;
    margin-right: 1rem;
  }

  .money {
    padding: 1rem 0;
    border-bottom: 1px solid #e8e8e8;
  }

  .money p {
    margin: 0;
    font-size: 14px;
    color: rgba(16, 16, 16, 1);
  }

  .money p span {
    color: rgb(64, 158, 255);
  }

  .money p span:last-child {
    margin-left: 4rem;
    cursor: pointer;
  }

  .el-tabs__nav-wrap::after {
    border: none;
  }
</style>

